package cn.maihe.elg.operation.service.business;

import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.bo.BidderCustomerBO;
import cn.maihe.elg.operation.model.enums.*;
import cn.maihe.elg.operation.model.vo.business.BidCustomerBO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerReportQueryVO;
import cn.maihe.elg.operation.model.vo.business.BidCustomerReportVO;
import cn.maihe.elg.operation.model.vo.business.ListBidCustomerVO;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.BidCustomerDOCondition;
import cn.maihe.elg.operation.repository.entity.BidCustomerVo;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDO;
import cn.maihe.elg.operation.repository.entity.UserDO;
import cn.maihe.elg.operation.repository.mapper.AcceptOrderInfoMapper;
import cn.maihe.elg.operation.repository.mapper.BidCustomerMapper;
import cn.maihe.elg.operation.repository.mapper.CustomerAttachmentMapper;
import cn.maihe.elg.operation.repository.mapper.UserMapper;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.service.system.UserService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.ElgLogger;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.UserContextUtil;
import cn.maihe.elg.operation.utils.ValidateUtil;
import cn.maihe.framework.starter.base.sql.PageBo;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 投标客户服务
 * @Author WJH
 * @Date 2021/03/25
 */
@Service
@Slf4j
public class BidCustomerService extends BaseDaoService<BidCustomerDO> {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BidCustomerMapper bidCustomerMapper;
    @Resource
    private CustomerAttachmentMapper customerAttachmentMapper;
    @Resource
    private UserService userService;
    @Resource
    private ExchangeCenterService exchangeCenterService;
    @Resource
    private CustomerAttachmentService customerAttachmentService;

    public PageBo<ListBidCustomerVO> selectPageBySql(int pageNo, int pageSize, ListBidCustomerVO vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        return this.selectPageBySql("selectBidCustomerList", "selectBidCustomerCount", paramsMap, pageNo, pageSize);
    }

    public boolean existsCreditCode(String creditCode, Long centerId, Long orgId, Long excludeSelfBidCustomerId) {
        Assert.notNull(creditCode, "统一社会信用代码不能为空");
        Assert.notNull(centerId, "centerId不能为空");
        Assert.notNull(orgId, "orgId不能为空");

        BidCustomerDOCondition condition = BidCustomerDOCondition.builder().andBidderCreditCodeEq(creditCode)
                .andCenterIdEq(centerId).andOrgIdEq(orgId);
        if (excludeSelfBidCustomerId != null) {
            condition.andIdNe(excludeSelfBidCustomerId);
        }
        return this.exists(condition.build());
    }

    /**
     * 多中心多出函机构共用投标企业信息
     *
     * @param creditCode
     * @param excludeSelfBidCustomerId
     * @return
     */
    public BidCustomerDO getByCreditCode(String creditCode, Long excludeSelfBidCustomerId) {
        Assert.notNull(creditCode, "统一社会信用代码不能为空");
//        Assert.notNull(orgId, "orgId不能为空");

        BidCustomerDOCondition condition = BidCustomerDOCondition.builder().andBidderCreditCodeEq(creditCode);
        return this.selectOne(condition.build());
    }

    /**
     * 区分出函机构
     *
     * @param creditCode
     * @param orgId
     * @param excludeSelfBidCustomerId
     * @return
     */
    public BidCustomerDO getByCreditCode(String creditCode, Long orgId, Long excludeSelfBidCustomerId) {
        Assert.notNull(creditCode, "统一社会信用代码不能为空");
        Assert.notNull(orgId, "orgId不能为空");

        BidCustomerDOCondition condition = BidCustomerDOCondition.builder().andBidderCreditCodeEq(creditCode)
                .andOrgIdEq(orgId);
        return this.selectOne(condition.build());
    }


    /**
     * 区分交易中心和出函机构
     *
     * @param creditCode
     * @param centerId
     * @param orgId
     * @param excludeSelfBidCustomerId
     * @return
     */
    public BidCustomerDO getByCreditCode(String creditCode, Long centerId, Long orgId, Long excludeSelfBidCustomerId) {
        Assert.notNull(creditCode, "统一社会信用代码不能为空");
        Assert.notNull(centerId, "centerId不能为空");
        Assert.notNull(orgId, "orgId不能为空");

        BidCustomerDOCondition condition = BidCustomerDOCondition.builder().andBidderCreditCodeEq(creditCode)
                .andCenterIdEq(centerId).andOrgIdEq(orgId);
        return this.selectOne(condition.build());
    }

    public Integer updateByCreditCode(BidCustomerDO bidCustomerDO) {
        Assert.notNull(bidCustomerDO, "bidCustomerDO不能为空");
        Assert.notNull(bidCustomerDO.getBidderCreditCode(), "统一社会信用代码不能为空");
        Assert.notNull(bidCustomerDO.getCenterId(), "centerId不能为空");
        Assert.notNull(bidCustomerDO.getOrgId(), "orgId不能为空");

        BidCustomerDOCondition condition = BidCustomerDOCondition.builder().andBidderCreditCodeEq(bidCustomerDO.getBidderCreditCode())
                .andCenterIdEq(bidCustomerDO.getCenterId()).andOrgIdEq(bidCustomerDO.getOrgId());

        return this.update(bidCustomerDO, condition.build());
    }

    public boolean existsBidCustomerLinkedAcceptOrder(Long bidCustomerId) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("bidCustomerId", bidCustomerId);
        return this.selectCountBySql("existsBidCustomerLinkedAcceptOrder", paramsMap) > 0;
    }

    public ListBidCustomerVO getBidCustomerDetailById(Long id) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("id", id);
        return this.selectOneBySql("getBidCustomerDetailById", paramsMap);
    }


    public BidCustomerDO saveOrUpdateBidCustomer(BidCustomerDO cur) {
        Assert.notNull(cur, "bidCustomerDO不能为空");
        Assert.notNull(cur.getBidderCreditCode(), "统一社会信用代码不能为空");
        Assert.notNull(cur.getCenterId(), "centerId不能为空");
        Assert.notNull(cur.getOrgId(), "orgId不能为空");
//        checkBidderContractInfo(cur);
        //投保客户在多中心间共享信息
        BidCustomerDO dbDo = this.getByCreditCode(cur.getBidderCreditCode(), null);
        if (dbDo != null) {
            log.info("bidderId:{} ，bidderName:{},修改前 {}", dbDo.getId(), dbDo.getBidderName(), dbDo);
            cur.setId(dbDo.getId());
            dbDo.setGmtModified(Date.from(Instant.now()));
            dbDo.setBidderName(cur.getBidderName());
            dbDo.setBidderCreditCode(cur.getBidderCreditCode());
            dbDo.setComTelArea(cur.getComTelArea());
            dbDo.setComTelNum(cur.getComTelNum());
            dbDo.setProvince(cur.getProvince());
            dbDo.setCity(cur.getCity());
            dbDo.setDistrict(cur.getDistrict());
            dbDo.setBidderEndDate(cur.getBidderEndDate());
            dbDo.setBidderContactName(cur.getBidderContactName());
            dbDo.setBidderContactTel(cur.getBidderContactTel());
            dbDo.setBidderContactIdcard(cur.getBidderContactIdcard());
            dbDo.setBidderContactIdcardType(cur.getBidderContactIdcardType());
            dbDo.setBidderAddress(cur.getBidderAddress());
            dbDo.setBidderEamil(cur.getBidderEamil());
            dbDo.setLegalPersonName(cur.getLegalPersonName());
            dbDo.setLegalPersonIdcard(cur.getLegalPersonIdcard());
            dbDo.setLegalPersonTel(cur.getLegalPersonTel());
            dbDo.setBeiandiquCode(cur.getBeiandiquCode());
            dbDo.setBankCardNum(cur.getBankCardNum());
            dbDo.setBankName(cur.getBankName());
            dbDo.setBankUserName(cur.getBankUserName());
            dbDo.setBidderRegAddress(cur.getBidderRegAddress());
            if (Objects.nonNull(cur.getCompleteFlag())) {
                dbDo.setCompleteFlag(cur.getCompleteFlag());
            }
            this.updateById(dbDo);
            log.info("bidderId:{} bidderName:{},修改后 {}", dbDo.getId(), dbDo.getBidderName(), dbDo);
        } else {
            cur.setStatus(BidCustomerStatus.REGIST.getStatus());
            cur.setId(cur.getId() != null ? cur.getId() : IdGenerate.getId());
            cur.setGmtCreate(Date.from(Instant.now()));
            cur.setGmtModified(cur.getGmtCreate());
            this.insert(cur);
        }
        return this.selectById(cur.getId());
    }

    public PageBo<BidCustomerReportVO> selectReportPageBySql(int pageNo, int pageSize, String gmtTimeRange, BidCustomerVo vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        if (StringUtils.isNotBlank(gmtTimeRange)) {
            String[] rangeAy = gmtTimeRange.split(",");
            if (rangeAy.length > 1) {
                paramsMap.put("startGmtTime", rangeAy[0] + " 00:00:00");
                paramsMap.put("endGmtTime", rangeAy[1] + " 23:59:59");
            }
        }
        PageBo<BidCustomerVo> bidCustomerVoPageBo = this.selectPageBySql("selectBidCustomerList", "selectBidCustomerCount", paramsMap, pageNo, pageSize);
        List<Long> ids = bidCustomerVoPageBo.getList().stream().map(BidCustomerVo::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            PageBo<BidCustomerReportVO> bidCustomerReportVOPageBo =
                    new PageBo<BidCustomerReportVO>(0,
                            0, new ArrayList<>());

            return bidCustomerReportVOPageBo;
        }
        paramsMap.put("bidCustomerIds", ids);
        List<Map> maps = MybatisDaoImpl.of(AcceptOrderInfoMapper.class).selectListBySql("selectBidCustomerReport", paramsMap);
        int size = maps.size();
        List<BidCustomerReportVO> bidCustomerReportVOS = bidCustomerVoPageBo.getList().stream().map(
                item -> {
                    BidCustomerReportVO bidCustomerReportVO = new BidCustomerReportVO();
                    bidCustomerReportVO.setBidderName(item.getBidderName());
                    bidCustomerReportVO.setBidCount(0l);
                    bidCustomerReportVO.setGuaranteeCount(0l);
                    for (int i = 0; i < size; i++) {
                        Map map = maps.get(i);
                        if (item.getId().longValue() == ((Long) map.get("bid_customer_id")).longValue()) {
                            bidCustomerReportVO.setBidCount((Long) map.get("bidCount"));
                            bidCustomerReportVO.setGuaranteeCount(((BigDecimal) map.get("guaranteeCount")).longValue());
                        }
                    }
                    return bidCustomerReportVO;
                }
        ).collect(Collectors.toList());
        PageBo<BidCustomerReportVO> bidCustomerReportVOPageBo =
                new PageBo<BidCustomerReportVO>(bidCustomerVoPageBo.getTotal(),
                        bidCustomerVoPageBo.getPages(), bidCustomerReportVOS);

        return bidCustomerReportVOPageBo;
    }

    public List<BidCustomerReportVO> listBidCustomerReportDownload(BidCustomerReportQueryVO vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        if (!CollectionUtils.isEmpty(vo.getGmtTimeRange())) {
            if (vo.getGmtTimeRange().size() > 1) {
                paramsMap.put("startGmtTime", vo.getGmtTimeRange().get(0) + " 00:00:00");
                paramsMap.put("endGmtTime", vo.getGmtTimeRange().get(1) + " 23:59:59");
            }
        }
        List<BidCustomerVo> vos = this.selectListBySql("selectBidCustomerList", paramsMap);
        List<Map> maps = MybatisDaoImpl.of(AcceptOrderInfoMapper.class).selectListBySql("selectBidCustomerReport", paramsMap);
        Map<Object, Map> totalMap = new HashMap<>();
        maps.forEach(item -> {
            totalMap.put(item.get("bid_customer_id"), item);
        });
        List<BidCustomerReportVO> bidCustomerReportVOS = vos.stream().map(
                item -> {
                    BidCustomerReportVO bidCustomerReportVO = new BidCustomerReportVO();
                    bidCustomerReportVO.setBidderName(item.getBidderName());
                    bidCustomerReportVO.setBidCount(0l);
                    bidCustomerReportVO.setGuaranteeCount(0l);
                    Map map = totalMap.get(item.getId());
                    if (map != null) {
                        bidCustomerReportVO.setBidCount((Long) map.get("bidCount"));
                        bidCustomerReportVO.setGuaranteeCount(((BigDecimal) map.get("guaranteeCount")).longValue());
                    }

                    return bidCustomerReportVO;
                }
        ).collect(Collectors.toList());
        return bidCustomerReportVOS;
    }

    @Transactional(rollbackFor = Exception.class)
    public void regist(BidCustomerDO bidCustomerDO, UserDO user, List<CustomerAttachmentDO> customerAttachmentDOS) {
        // 判断登录账号和状态判断是否重复
        Integer countUserName = userMapper.selectCount(new EntityWrapper<UserDO>()
                .eq("username", user.getUsername())
                .ne("status", UserStatusEnum.DELETED.toString()));
        if (countUserName > 0) {
            log.error("创建用户失败， 登录账号重复");
            throw new SystemRuntimeException(ErrorCode.BSMUM001, user.getUsername());
        }
        //todo 统一信用代码校验
        Integer countBidder = bidCustomerMapper.selectCount(BidCustomerDOCondition.builder()
                .andBidderCreditCodeEq(bidCustomerDO.getBidderCreditCode())
                .build());
        if (countBidder > 0) {
            log.error("创建投标企业失败，统一信用代码重复");
            throw new SystemRuntimeException(ErrorCode.EXISTS, "投标企业统一信用代码", bidCustomerDO.getBidderCreditCode());
        }

        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setPwdExpiredTime(DateUtil.getDayAfter(90));
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());
        bidCustomerDO.setCenterId(Constants.CENTER_ID);
        bidCustomerDO.setOrgId(Constants.ORG_ID);
        bidCustomerDO.setStatus(BidCustomerStatus.AUDIT_INNER.getStatus());
        bidCustomerDO.setGmtCreate(new Date());
        bidCustomerDO.setGmtModified(new Date());
        user.setId(IdGenerate.getId());
        user.setOrgId(bidCustomerDO.getId());
//        bidCustomerDO.setUserCreate());
        bidCustomerMapper.insert(bidCustomerDO);
        userMapper.insert(user);
        //未审核 暂不分配权限
//        userMapper.insertUserRole(RoleType.BIDDER.getType(), user.getId());
        customerAttachmentDOS.forEach(item -> customerAttachmentMapper.insert(item));

    }

    @Transactional(rollbackFor = Exception.class)
    public void modify(BidCustomerDO cDO, List<CustomerAttachmentDO> updateList, List<CustomerAttachmentDO> createList) {
        //企业基本户信息 取值 开户许可证信息
        cDO.setBankName(cDO.getLicenseBank());
        cDO.setBankCardNum(cDO.getLicenseAccount());
        bidCustomerMapper.updateById(cDO);
        updateList.forEach(item -> customerAttachmentMapper.updateById(item));
        createList.forEach(item -> customerAttachmentMapper.insert(item));

    }

    @Transactional(rollbackFor = Exception.class)
    public void update(BidCustomerDO cDO, List<CustomerAttachmentDO> updateList, List<CustomerAttachmentDO> createList) {
//        cDO.setLegalPersonTel(cDO.getBidderContactTel());
        //企业基本户信息 取值 开户许可证信息
        cDO.setBankName(cDO.getLicenseBank());
        cDO.setBankCardNum(cDO.getLicenseAccount());

        UserContext uc = UserContextUtil.getUserContext();
        if (UserType.BIDDER.getType() != uc.getUserType()) {
            //新增非投标人操作已认证可直接修改投标人信息
            if (cDO.getStatus() != null && cDO.getStatus() == BidCustomerStatus.NORMAL.getStatus()) {
                cDO.setStatus(BidCustomerStatus.NORMAL.getStatus());
                cDO.setUserModified(uc.getUsername() + " 正常情况下直接编辑生效");
                this.updateById(cDO);
            } else {
                cDO.setStatus(BidCustomerStatus.AUDIT_INNER.getStatus());
                bidCustomerMapper.update(cDO, BidCustomerDOCondition.builder().andIdEq(cDO.getId())
                        .andStatusIn(BidCustomerStatus.AUDIT_FAIL.getStatus(), BidCustomerStatus.AUDIT_INNER.getStatus(), BidCustomerStatus.REGIST.getStatus()).build());
            }
        } else {
            cDO.setStatus(BidCustomerStatus.AUDIT_INNER.getStatus());
            bidCustomerMapper.update(cDO, BidCustomerDOCondition.builder().andIdEq(cDO.getId())
                    .andStatusIn(BidCustomerStatus.AUDIT_FAIL.getStatus(), BidCustomerStatus.REGIST.getStatus()).build());
        }


        updateList.forEach(item -> customerAttachmentMapper.updateById(item));
        createList.forEach(item -> customerAttachmentMapper.insert(item));
    }


    /**
     * 投标客户审核通过，更新投标客户信息，添加用户权限
     *
     * @param cDO
     */
    @Transactional(rollbackFor = Exception.class)
    public void customerSuccess(BidCustomerDO cDO) {
        UserDO userDO = new UserDO();
        userDO.setOrgId(cDO.getId());
        userDO = userMapper.selectOne(userDO);
        if (userDO == null) {
            throw new SystemRuntimeException(ErrorCode.BSMUM003, cDO.getBidderContactTel());
        }

        userMapper.insertUserRole(RoleType.BIDDER.getType(), userDO.getId());
        cDO.setStatus(AuditStatusEnum.AUDITED.getValue());
        this.updateById(cDO);
    }

    public long totalAudit() {
        Map<String, Object> paramsMap = toMapAndAddParams(new HashMap());
        return this.selectCountBySql("auditTotal", paramsMap);
    }

    /**
     * @param bo 投标企业信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BidderCustomerBO saveBidderCustomerBO(BidderCustomerBO bo) {
        ValidateUtil.validate(bo);

        //保存&更新投标客户
        BidCustomerDO curBidCustomer = this.saveOrUpdateBidCustomer(bo.getBidCustomer());
        bo.setBidCustomer(curBidCustomer);

        //保存或更新投标客户登录账号：登录账号：社会信用代码 密码默认123456
        bo.getUserDO().setOrgId(curBidCustomer.getId());
        userService.saveOrUpdateBidUser(bo.getUserDO());

        return bo;
    }

    public Boolean isCompleteCustomerInfo(AcceptOrderInfoDO acceptOrderInfoDO, BidCustomerDO bidCustomerDO) {
        if (Objects.isNull(acceptOrderInfoDO) || Objects.isNull(bidCustomerDO)) {
            return false;
        }

        CenterNoEnum centerNoEnum = exchangeCenterService.getCenterNoEnumById(acceptOrderInfoDO.getCenterId());
        boolean centerResult = centerNoEnum == CenterNoEnum.NANPING || centerNoEnum == CenterNoEnum.LONGYAN || centerNoEnum == CenterNoEnum.PUTIAN || CreateGuaranteeUtil.isSuiXing(centerNoEnum, acceptOrderInfoDO.getClientId());

        if (centerResult && Objects.equals(bidCustomerDO.getStatus(), 1) && Objects.equals(bidCustomerDO.getCompleteFlag(), 0)) {
            return true;
        } else {
            return false;
        }
    }

    public Boolean isUpdateCompleteFlag(BidCustomerDO bidCustomerDO) {
        if (Objects.isNull(bidCustomerDO)) {
            return false;
        }
        return Objects.equals(bidCustomerDO.getStatus(), 1) && Objects.equals(bidCustomerDO.getCompleteFlag(), 0);
    }

    /**
     * 校验投保客户联系人姓名、手机号、身份证号、注册地址、邮箱地址在系统中的唯一性
     *
     * @param curDO 需要校验的投保客户信息
     */
    public void checkBidderContractInfo(BidCustomerDO curDO) {
        BidCustomerDO bidCustomerDO = getByCreditCode(curDO.getBidderCreditCode(), curDO.getOrgId(), null);
        List<BidCustomerDO> bidderContactIdCardRepeatList;
        if (bidCustomerDO != null) {
            bidderContactIdCardRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderContactIdcardEq(curDO.getBidderContactIdcard())
                    .and().andIdNe(bidCustomerDO.getId())
                    .build());
        } else {
            bidderContactIdCardRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderContactIdcardEq(curDO.getBidderContactIdcard())
                    .build());
        }
        if (!CollectionUtils.isEmpty(bidderContactIdCardRepeatList)) {
            ElgLogger.error(log, l -> l.error("投保客户[{}]联系人身份证号{}唯一性校验失败", curDO.getBidderName(), curDO.getBidderContactIdcard()));
            throw new RuntimeException("投保客户联系人身份证号["+bidderContactIdCardRepeatList.get(0).getBidderContactIdcard()+"]已被其他企业["+bidderContactIdCardRepeatList.get(0).getBidderName()+"]使用，请修改后重新申请订单或联系客服处理");
        }

        List<BidCustomerDO> bidderContactTelRepeatList;
        if (bidCustomerDO != null) {
            bidderContactTelRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderContactTelEq(curDO.getBidderContactTel())
                    .and().andIdNe(bidCustomerDO.getId())
                    .build());
        } else {
            bidderContactTelRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderContactTelEq(curDO.getBidderContactTel())
                    .build());
        }
        if (!CollectionUtils.isEmpty(bidderContactTelRepeatList)) {
            ElgLogger.error(log, l -> l.error("投保客户[{}]联系人手机号{}唯一性校验失败", curDO.getBidderName(), curDO.getBidderContactTel()));
            throw new RuntimeException("投保客户联系人手机号["+bidderContactTelRepeatList.get(0).getBidderContactTel()+"]已被其他企业["+bidderContactTelRepeatList.get(0).getBidderName()+"]使用，请修改后重新申请订单或联系客服处理");
        }


        List<BidCustomerDO> bidderEmailRepeatList;
        if (bidCustomerDO != null) {
            bidderEmailRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderEamilEq(curDO.getBidderEamil())
                    .and().andIdNe(bidCustomerDO.getId())
                    .build());
        } else {
            bidderEmailRepeatList = bidCustomerMapper.selectList(BidCustomerDOCondition.builder()
                    .orBidderEamilEq(curDO.getBidderEamil())
                    .build());
        }
        if (!CollectionUtils.isEmpty(bidderEmailRepeatList)) {
            ElgLogger.error(log, l -> l.error("投保客户[{}]联系人电子邮箱{}唯一性校验失败", curDO.getBidderName(), curDO.getBidderEamil()));
            throw new RuntimeException("投保客户电子邮箱["+bidderEmailRepeatList.get(0).getBidderEamil()+"]已被其他企业["+bidderEmailRepeatList.get(0).getBidderName()+"]使用，请修改后重新申请订单或联系客服处理");
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateByFreeLogin(BidCustomerDO cDO, List<CustomerAttachmentDO> updateList, List<CustomerAttachmentDO> createList) {
        //企业基本户信息 取值 开户许可证信息
        cDO.setBankName(cDO.getLicenseBank());
        cDO.setBankCardNum(cDO.getLicenseAccount());
        UserContext uc = UserContext.create(
                String.valueOf(cDO.getId()),
                        cDO.getBidderCreditCode(),
                        null,
                        null,
                         UserType.BIDDER.getType(),
                        null,
                        null,
                cDO.getOrgId(),
                        null,
                        null,
                        null,
                        null,
                        null,
                        null
        );
        if (UserType.BIDDER.getType() != uc.getUserType()) {
            //新增非投标人操作已认证可直接修改投标人信息
            if (cDO.getStatus() != null && cDO.getStatus() == BidCustomerStatus.NORMAL.getStatus()) {
                cDO.setStatus(BidCustomerStatus.NORMAL.getStatus());
                cDO.setUserModified(uc.getUsername() + " 正常情况下直接编辑生效");
                this.updateById(cDO);
            } else {
                cDO.setStatus(BidCustomerStatus.AUDIT_INNER.getStatus());
                bidCustomerMapper.update(cDO, BidCustomerDOCondition.builder().andIdEq(cDO.getId())
                        .andStatusIn(BidCustomerStatus.AUDIT_FAIL.getStatus(), BidCustomerStatus.AUDIT_INNER.getStatus(), BidCustomerStatus.REGIST.getStatus()).build());
            }
        } else {
            cDO.setStatus(BidCustomerStatus.AUDIT_INNER.getStatus());
            bidCustomerMapper.update(cDO, BidCustomerDOCondition.builder().andIdEq(cDO.getId())
                    .andStatusIn(BidCustomerStatus.AUDIT_FAIL.getStatus(), BidCustomerStatus.REGIST.getStatus()).build());
        }


        updateList.forEach(item -> customerAttachmentMapper.updateById(item));
        createList.forEach(item -> customerAttachmentMapper.insert(item));
    }

    /**
     * 查询投标企业附件url
     * @param id
     * @param bidCustomerDO
     * @return
     */
    public BidCustomerBO getBidCustomerBO(Long id, BidCustomerDO bidCustomerDO) {
        BidCustomerBO bidCustomerBO = new BidCustomerBO();
        BeanUtils.copyProperties(bidCustomerDO, bidCustomerBO);

        List<CustomerAttachmentDO> customerAttachmentDOS = customerAttachmentService.getAttachmentDO(id, null);

        customerAttachmentDOS.forEach(attach -> {
            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
            switch (type) {
                case TYPE_0:
                    bidCustomerBO.setBusinessLicensePic(attach.getAttachFileName());
                    break;
                case TYPE_1:
                    bidCustomerBO.setAccountOpenLicensePic(attach.getAttachFileName());
                    break;
                case TYPE_2:
                    bidCustomerBO.setLegalIdcardPic(attach.getAttachFileName());
                    break;
                case TYPE_3:
                    bidCustomerBO.setLegalIdcard1Pic(attach.getAttachFileName());
                    break;
                case TYPE_4:
                    bidCustomerBO.setApplyPic(attach.getAttachFileName());
                    break;
                case TYPE_5:
                    bidCustomerBO.setContactPic(attach.getAttachFileName());
                    break;
                case TYPE_6:
                    bidCustomerBO.setAuthPic(attach.getAttachFileName());
                    break;
                case TYPE_7:
                    bidCustomerBO.setQualificationPic(attach.getAttachFileName());
                    break;
            }

        });
        return bidCustomerBO;
    }
}
